package com.hwadee.teachingprocessmanagementsystem.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Calendar;
import java.util.Map;

/**
 * @Description: JWT工具类
 * @Author: Jukomu
 * @Package: org.csu.mypetstore.utils
 * @Project: MyPetStore-SSM
 * @name: JWTUtils
 * @Date: 2024/4/1 1:46
 * @Filename: JWTUtils
 */
public class JWTUtils {


    private static final String SING = "!Q@W3e4r%T^Y";

    /**
     * 生成token  header.payload.sing
     * 默认2小时过期
     * @param map
     */
    public static String getToken(Map<String, String> map) {

        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.HOUR, 2);//默认2小时过期

        //创建jwt builder
        JWTCreator.Builder builder = JWT.create();

        //payload
        map.forEach(builder::withClaim);

        return builder.withExpiresAt(instance.getTime())//指定令牌过期时间
                .sign(Algorithm.HMAC256(SING));
    }

    /**
     * 指定令牌过期时间
     * @param map
     * @param instance
     */
    public static String getToken(Map<String, String> map, Calendar instance) {

        //创建jwt builder
        JWTCreator.Builder builder = JWT.create();

        //payload
        map.forEach(builder::withClaim);

        return builder.withExpiresAt(instance.getTime())//指定令牌过期时间
                .sign(Algorithm.HMAC256(SING));
    }

    /**
     * 验证token 合法性
     */
    public static DecodedJWT verify(String token) {
        return JWT.require(Algorithm.HMAC256(SING)).build().verify(token);
    }
}
